const browser = require('../browser');
const fs = require('fs');
const path = require('path');
const { logger } = require('../../utils/logger');

const CONFIG = {
  TARGET_URL: 'https://www.doubao.com/chat/create-image',
  INPUT_SELECTOR: 'div.editor-wrapper-AdiwSu > div > div',
  STREAM_URL: 'https://www.doubao.com/samantha/chat/completion'
};

class PuppeteerDoubao {
  static async generateImages(prompt, options = {}) {
    let downloadCompleted = false;
    logger.info('开始生成豆包图片');
    return browser.runWithPuppeteer(CONFIG.TARGET_URL, {
      width: 1280,
      height: 720,
      delay: 3000,
      waitUntil: 'domcontentloaded',
      ...options
    }, async (page) => {
      // 设置请求拦截
      await page.setRequestInterception(true);
      
      page.on('request', request => request.continue());
      page.on('response', async (response) => {
        if (!response.url().includes(CONFIG.STREAM_URL)) return;
        
        try {
          const text = await response.text();
          if (text.includes('x-signature')) {
            logger.info('识别到 x-signature 开始解析豆包图片');
            await this.parseAndDownloadImages(text, page);
            downloadCompleted = true;
          }
        } catch (error) {
          logger.error('处理响应失败:', error.message);
        }
      });

      // 提交内容
      await page.waitForSelector(CONFIG.INPUT_SELECTOR, { timeout: 15000 });
      await page.click(CONFIG.INPUT_SELECTOR);
      await page.evaluate((text) => navigator.clipboard.writeText(text), prompt);
      await page.keyboard.down('Control');
      await page.keyboard.press('KeyV');
      await page.keyboard.up('Control');
      await browser.wait(500);
      await page.keyboard.press('Enter');
      logger.info('提交内容完成');
      
      // 等待下载完成
      const timeout = options.timeout || 60000;
      const startTime = Date.now();
      while (!downloadCompleted && (Date.now() - startTime) < timeout) {
        await browser.wait(1000);
      }
      
      logger.info(`Puppeteer豆包图片生成: ${downloadCompleted ? '成功' : '超时'}`);
      
      return { success: downloadCompleted };
    });
  }

  static async parseAndDownloadImages(responseText, page) {
    const lines = responseText.split('\n');
    
    for (const line of lines) {
      if (!line.startsWith('data: ') || !line.includes('creations')) continue;
      
      try {
        const data = JSON.parse(line.substring(6));
        const eventData = JSON.parse(data.event_data || '{}');
        const content = JSON.parse(eventData.message?.content || '{}');
        
        if (!content.creations?.length) continue;
        
        const downloadDir = path.join(__dirname, 'downloads');
        if (!fs.existsSync(downloadDir)) {
          fs.mkdirSync(downloadDir, { recursive: true });
        }
        
        for (let i = 0; i < content.creations.length; i++) {
          const creation = content.creations[i];
          if (creation.type !== 1 || !creation.image?.image_preview?.url) continue;
          
          const { image_preview } = creation.image;
          const filename = `image_${i + 1}_${Date.now()}.${image_preview.format}`;
          
          const response = await page.goto(image_preview.url);
          const buffer = await response.buffer();
          fs.writeFileSync(path.join(downloadDir, filename), buffer);
          
          logger.info(`Puppeteer图片下载完成: ${filename}`);
        }
      } catch (error) {
        logger.warn('解析数据失败:', error.message);
      }
    }
  }
}

module.exports = PuppeteerDoubao;
